import {defineStore} from 'pinia'
import {isElementInViewport, isScrollToBottom} from '~/utils/dom'

const DEFAULT_PAGE_KEY = 'recommended'

export const useSystemStore = defineStore('systemStore',{
  state:()=>({
    categoryIndex: 0,
    categoryPageKey: DEFAULT_PAGE_KEY,
    categoryId: 0,
    categoryList: [],
    indexNewsDataLoaded: false,
    indexArticlesDataLoaded: false,
    topViewNav: false,
    showMainNav: true,
    showBackTop: false,
    reachBottom: false,
    siteInfo: {}
  }),
  getters: {
    currentCategoryId: (state) => {
      let categoryId
      for (const obj of state.categoryList) {
        if (state.categoryPageKey === obj.key) {
          categoryId = obj.id
          break
        }
      }
      return categoryId
    }
  },
  // getters:{
  //   cate: (state) => state.categoryIndex
  // },
  actions:{
    resetCategoryVars() {
       this.categoryIndex = 0
       this.categoryPageKey = DEFAULT_PAGE_KEY
       this.categoryId =  0
    },
    setCategoryIndex(url: string) {
      for (const obj of this.categoryList) {
        if (url === obj.url) {
          this.categoryId = obj.id
          this.categoryPageKey = obj.key
          this.categoryIndex = obj.user
          break
        }
      }
    },
    onWindowScroll() {
      // 首页列表图片拦截在
      this.homePageImageLazyLoad()
      const y = window.scrollY
      this.topViewNav = y > 320
      this.showBackTop = y > 380
      this.showMainNav = y < 320
      this.reachBottom = isScrollToBottom()
    },
    homePageImageLazyLoad() {
      const lazyImages = document.querySelectorAll('.entry-list .lazy img')
      lazyImages.forEach(image => {
        if (isElementInViewport(image)) {
          loadImage(image)
        }
      })
    }
  },
})

const loadImage = (image) => {
  const imgSrc = image.dataset.src
  if (imgSrc) {
    image.src = imgSrc
    image.removeAttribute('data-src')
  }
  const wrapperEl = image.parentElement
  if (wrapperEl.classList.contains('lazy')) {
    wrapperEl.classList.remove('lazy')
    wrapperEl.classList.add('loaded')
  }
}
